package com.example.syyao.myapp.Personal;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import android.util.Base64;

import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.donkingliang.labels.LabelsView;
import com.example.syyao.myapp.R;

import com.example.syyao.myapp.Response.Get_response;
import com.example.syyao.myapp.Tool.MyGlideEngine;
import com.example.syyao.myapp.WebContact.JsonUtil;
import com.example.syyao.myapp.WebContact.WebAccessTools;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;;


import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import static com.example.syyao.myapp.MainActivity.MODE;
import static com.example.syyao.myapp.MainActivity.PREFERENCE_NAME;

public class Personal_send extends SwipeBackActivity {

    private static final int REQUEST_CODE_CHOOSE = 23;

    TextView textView;
    Button button;
    private UriAdapter mAdapter;
    LabelsView labelsView;
    ArrayList<String> Tag;
    TextView send;
    TextView back;
    List<Uri> uris;
    Get_response sign_in_response;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_send);

        overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_right);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }

        textView = (TextView) findViewById(R.id.textview_send);
        button = (Button) findViewById(R.id.button_select_picture);
        send = (TextView) findViewById(R.id.txt_send);
        back = (TextView) findViewById(R.id.txt_back);

        send.setOnClickListener(new sendClick());
        back.setOnClickListener(new backClick());

        labelsView = (LabelsView) findViewById(R.id.labels);
        uris = new ArrayList<>();
        Tag = new ArrayList<>();
//        label.add("Android");
//        label.add("IOS");
//        label.add("前端");
//        label.add("后台");
//        label.add("微信开发");
//        label.add("游戏开发");
//        labelsView.setLabels(label); //直接设置一个字符串数组就可以了。

//LabelsView可以设置任何类型的数据，而不仅仅是String。
        ArrayList<String> testList = new ArrayList<>();
        testList.add("汪汪");
        testList.add("小坏坏");
        testList.add("假的");
        testList.add("小仓鼠");
        testList.add("滑稽");
        testList.add("咸鱼");
        testList.add("熊猫");
        testList.add("蘑菇头");
        testList.add("可达鸭");
        labelsView.setLabels(testList, new LabelsView.LabelTextProvider<String>() {
            @Override
            public CharSequence getLabelText(TextView label, int position, String data) {
                return data;
            }

        });
        labelsView.setOnLabelClickListener(new LabelsView.OnLabelClickListener() {
            @Override
            public void onLabelClick(TextView label, Object data, int position) {

                for (int i = 0; i < Tag.size(); i++) {
                    if (Tag.get(i) == data.toString()) {
                        Tag.remove(i);
                        return;
                    }
                }
                Tag.add(String.valueOf(data));

            }
        });


        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setAdapter(mAdapter = new UriAdapter());


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Matisse
                        .from(Personal_send.this)
                        .choose(MimeType.ofAll())//照片视频全部显示
                        .countable(true)//有序选择图片
                        .maxSelectable(9)//最大选择数量为9
                        // .gridExpectedSize(120)//图片显示表格的大小getResources()
                        .thumbnailScale(0.85f)//缩放比例
                        .theme(R.style.Matisse_Zhihu)//主题  暗色主题 R.style.Matisse_Dracula
                        .imageEngine(new MyGlideEngine())//加载方式
                        .forResult(REQUEST_CODE_CHOOSE);//请求码
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mAdapter.setData(Matisse.obtainResult(data));
            uris = Matisse.obtainResult(data);
        }
    }


    private class UriAdapter extends RecyclerView.Adapter<UriAdapter.UriViewHolder> {

        private List<Uri> mUris;

        void setData(List<Uri> uris) {
            mUris = uris;
            notifyDataSetChanged();
        }

        @Override
        public UriViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new UriViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item, parent, false));
        }

        @Override
        public void onBindViewHolder(UriViewHolder holder, int position) {
            Glide.with(Personal_send.this).load(mUris.get(position)).into(holder.mImg);
        }

        @Override
        public int getItemCount() {
            return mUris == null ? 0 : mUris.size();
        }

        class UriViewHolder extends RecyclerView.ViewHolder {

            private ImageView mImg;

            UriViewHolder(View contentView) {
                super(contentView);
                mImg = (ImageView) contentView.findViewById(R.id.img);
            }
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0,R.anim.slide_out_right);
    }

    private class backClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            finish();
        }
    }

    private class sendClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (Tag.size() == 0) {
                Toast.makeText(Personal_send.this, R.string.chickTag, Toast.LENGTH_SHORT).show();
                return;
            }
            if (uris.size() == 0) {
                Toast.makeText(Personal_send.this, R.string.chickPhoto, Toast.LENGTH_SHORT).show();
                return;
            }
            upload();
        }
    }

    private void upload() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                int number = uris.size();
                int tagNumber=Tag.size();
                String[] pic = new String[number];
                String[] tag = new String[tagNumber];
                for (int i = 0; i < number; i++) {
                    try {
                        pic[i]=bitmapToBase64(MediaStore.Images.Media.getBitmap(getContentResolver(),uris.get(i)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                for(int i=0;i<tagNumber;i++){
                    tag[i]=Tag.get(i);
                    System.out.println(tag[i]);
                }

                SharedPreferences sharedPreferences=getSharedPreferences(PREFERENCE_NAME,MODE);
                String username = sharedPreferences.getString("username","1");

                String webContent = WebAccessTools.photo(tag,pic,username);
                System.out.println(webContent);
                sign_in_response = (Get_response) JsonUtil.jsonToObject(webContent,
                        Get_response.class);
                handler.sendEmptyMessage(0x123);

            }
        }).start();

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (sign_in_response != null && sign_in_response.getMessage().equals("成功")) {
                Toast.makeText(Personal_send.this, "发送成功！", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                intent.setAction("action.refreshActivity_A");
                sendBroadcast(intent);
                finish();

            }
        }

        ;
    };


    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
                baos.flush();
                baos.close();
                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


}
